// Constants
const SESSION_UNLOCKED_KEY = "sessionUnlocked";
const BOOKMARK_COUNT_KEY = "bookmarkCount";
const FEEDBACK_DISABLED_KEY = "feedbackDisabled";
const CHROME_STORE_URL =
  "https://chromewebstore.google.com/detail/private-bookmark-locker/fagjclghcmnfinjdkdnkejodfjgkpljd/reviews";
const BOOKMARK_SWITCH_KEY = "switchKey";

// DOMContentLoaded initialization
document.addEventListener("DOMContentLoaded", () => {
  localizeHtmlPage();
  initializePopup();
  initializeLock();
  initializeFeedback();
  turnOffWarning();
  trunOffInstructions();
});

function turnOffWarning() {
  const warning = document.getElementById("passwordWarning");
  chrome.storage.local.get(["hash", "salt"], (result) => {
    const passwordSet = result.hash && result.salt;
    if (passwordSet) {
      warning.classList.add("hidden");
    }
  });
}

function trunOffInstructions() {
  const instructions = document.getElementById("instructions");
  chrome.storage.local.get(["bookmarks"], (result) => {
    const bookmarks = result.bookmarks || [];
    if (bookmarks && bookmarks.length > 0) {
      instructions.classList.add("hidden");
    } else {
      instructions.classList.remove("hidden");
    }
  });
}

chrome.storage.onChanged.addListener((changes, area) => {
  if (area === "local" && "bookmarks" in changes) {
    displayBookmarks();
  }
});

function localizeHtmlPage() {
  const elements = document.querySelectorAll("[data-i18n]");
  elements.forEach((el) => {
    const messageKey = el.getAttribute("data-i18n");
    const message = chrome.i18n.getMessage(messageKey);
    if (message) {
      if (
        el.tagName.toLowerCase() === "input" ||
        el.tagName.toLowerCase() === "textarea"
      ) {
        el.setAttribute("placeholder", message);
      } else if (el.tagName.toLowerCase() === "title") {
        document.title = message;
      } else {
        el.textContent = message;
      }
    }
  });
}

// Popup logic
function initializePopup() {
  const lockButton = document.getElementById("lockButton");
  const saveButton = document.getElementById("saveCurrentPage");
  const backupButton = document.getElementById("backupButton");
  const insertDividerTopBtn = document.getElementById("insertDividerTopBtn");
  const dividerDialog = document.getElementById("dividerDialog");
  const dividerDialogInput = document.getElementById("dividerDialogInput");
  const dividerDialogOk = document.getElementById("dividerDialogOk");
  const dividerDialogCancel = document.getElementById("dividerDialogCancel");
  const checkLatencyBtn = document.getElementById("checkLatencyBtn");

  // Check if password is not set, show initial setup
  chrome.storage.local.get(["hash", "salt"], (result) => {
    if (!result.hash || !result.salt) {
      showInitialPasswordSetup();
    }
  });

  // Event listeners
  lockButton.addEventListener("click", () => {
    // Set session flag to false to lock the extension
    chrome.storage.session.set({ [SESSION_UNLOCKED_KEY]: false }, () => {
      // Show the lock overlay
      showLockOverlay();
    });
  });
  saveButton.addEventListener("click", saveCurrentPage);
  backupButton.addEventListener("click", showBackupDialog);
  if (insertDividerTopBtn) {
    insertDividerTopBtn.onclick = () => {
      dividerDialogInput.value = '';
      dividerDialog.classList.remove('hidden');
      dividerDialog.classList.add('flex');
      dividerDialogInput.focus();
    };
  }
  if (dividerDialogCancel) {
    dividerDialogCancel.onclick = () => {
      dividerDialog.classList.remove('flex');
      dividerDialog.classList.add('hidden');
    };
  }
  if (dividerDialogOk) {
    dividerDialogOk.onclick = () => {
      const text = dividerDialogInput.value.trim();
      chrome.storage.local.get(["bookmarks"], (result) => {
        const bookmarks = result.bookmarks || [];
        bookmarks.push({ type: 'divider', text });
        chrome.storage.local.set({ bookmarks }, displayBookmarks);
        dividerDialog.classList.remove('flex');
        dividerDialog.classList.add('hidden');
      });
    };
  }
  // 支持回车直接确定
  if (dividerDialogInput) {
    dividerDialogInput.onkeypress = (e) => {
      if (e.key === 'Enter') dividerDialogOk.onclick();
    };
  }
  if (checkLatencyBtn) {
    checkLatencyBtn.onclick = async () => {
      checkLatencyBtn.disabled = true;
      checkLatencyBtn.title = '检测中...';
      window.latencyResults = {};
      displayBookmarks();
      chrome.storage.local.get(["bookmarks"], async (result) => {
        const bookmarks = result.bookmarks || [];
        const tests = bookmarks.map(async (b, idx) => {
          if (!b.url) return;
          const url = b.url;
          const start = Date.now();
          let ok = false;
          let latency = null;
          try {
            const controller = new AbortController();
            const timeout = setTimeout(() => controller.abort(), 6000);
            await fetch(url, { method: 'HEAD', mode: 'no-cors', signal: controller.signal });
            clearTimeout(timeout);
            ok = true;
            latency = Date.now() - start;
          } catch (e) {
            latency = '超时';
          }
          window.latencyResults[url] = ok ? latency + 'ms' : '超时';
          displayBookmarks();
        });
        await Promise.all(tests);
        checkLatencyBtn.disabled = false;
        checkLatencyBtn.title = '检测所有网址延迟';
      });
    };
  }
  window.onload = displayBookmarks;
}

// Initial password setup
function showInitialPasswordSetup() {
  const lockOverlay = document.getElementById("lockOverlay");
  const submitPassword = document.getElementById("submitPassword");
  const passwordInput = document.getElementById("passwordInput");

  document.querySelector("#lockOverlay h2").textContent =
    chrome.i18n.getMessage("app_create_password");
  submitPassword.textContent = chrome.i18n.getMessage("app_set_password");
  passwordInput.placeholder = chrome.i18n.getMessage(
    "app_create_password_placeholder"
  );

  lockOverlay.classList.remove("hidden");
  lockOverlay.classList.add("flex", "flex-col");
  passwordInput.focus();

  submitPassword.onclick = async () => {
    const input = document.getElementById("passwordInput").value;
    if (input.length < 4) {
      showError(chrome.i18n.getMessage("app_pass_short_error"));
      return;
    }

    await savePassword(input); // Save salt + hash
    hideLockOverlay();
  };

  passwordInput.onkeypress = (e) => {
    if (e.key === "Enter") submitPassword.onclick();
  };
}

// Lock check logic
function initializeLock() {
  chrome.storage.local.get(["hash", "salt"], (result) => {
    const passwordSet = result.hash && result.salt;
    chrome.storage.session.get([SESSION_UNLOCKED_KEY], (sessionResult) => {
      const unlocked = sessionResult[SESSION_UNLOCKED_KEY];
      if (passwordSet && !unlocked) showLockOverlay();
    });
  });

  const submitPassword = document.getElementById("submitPassword");
  const passwordInput = document.getElementById("passwordInput");

  submitPassword.addEventListener("click", handlePasswordSubmit);
  passwordInput.addEventListener("keypress", (e) => {
    if (e.key === "Enter") handlePasswordSubmit();
  });
}

// Lock overlay functions
function showLockOverlay() {
  const overlay = document.getElementById("lockOverlay");
  const input = document.getElementById("passwordInput");
  const error = document.getElementById("passwordError");
  if (!overlay || !input || !error) return; // 防止DOM未找到时报错

  overlay.classList.remove("hidden");
  overlay.classList.add("flex", "flex-col");
  input.value = "";
  input.placeholder = chrome.i18n.getMessage("app_enter_password_placeholder");
  error.classList.add("hidden");
  input.focus();
}

function hideLockOverlay() {
  const overlay = document.getElementById("lockOverlay");
  if (!overlay) return;
  overlay.classList.remove("flex", "flex-col");
  overlay.classList.add("hidden");
}

function showError(msg) {
  const error = document.getElementById("passwordError");
  error.textContent = msg;
  error.classList.remove("hidden");
}

// Crypto functions
function generateSalt(length = 16) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return btoa(String.fromCharCode(...array));
}

async function hashPassword(password, salt) {
  const encoder = new TextEncoder();
  const data = encoder.encode(password + salt);
  const buffer = await crypto.subtle.digest("SHA-256", data);
  const byteArray = Array.from(new Uint8Array(buffer));
  return btoa(String.fromCharCode(...byteArray));
}

async function savePassword(password) {
  const salt = generateSalt();
  const hash = await hashPassword(password, salt);
  chrome.storage.local.set({ salt, hash }, () => {
    chrome.storage.session.set(
      { [SESSION_UNLOCKED_KEY]: true },
      hideLockOverlay
    );
  });
}

async function checkPassword(inputPassword) {
  return new Promise((resolve) => {
    chrome.storage.local.get(["salt", "hash"], async (result) => {
      if (!result.salt || !result.hash) return resolve(false);
      const inputHash = await hashPassword(inputPassword, result.salt);
      resolve(inputHash === result.hash);
    });
  });
}

async function handlePasswordSubmit() {
  const input = document.getElementById("passwordInput").value;
  if (input.length < 4) {
    showError(chrome.i18n.getMessage("app_pass_short_error"));
    return;
  }

  chrome.storage.local.get(["hash", "salt"], async (result) => {
    if (!result.hash || !result.salt) {
      await savePassword(input); // first time
    } else {
      const valid = await checkPassword(input);
      if (valid) {
        chrome.storage.session.set(
          { [SESSION_UNLOCKED_KEY]: true },
          hideLockOverlay
        );
      } else {
        showError(chrome.i18n.getMessage("app_pass_incorrect_error"));
      }
    }
  });
}

// Bookmark logic
function saveCurrentPage() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    const tab = tabs[0];
    const { url, title, incognito } = tab;

    // 弹出prompt让用户输入自定义名称
    let customTitle = prompt('请输入书签名称（可自定义）：', title);
    if (customTitle === null) {
      // 用户取消，不保存
      return;
    }
    customTitle = customTitle.trim() || title;

    chrome.storage.local.get(
      ["bookmarks", BOOKMARK_COUNT_KEY, FEEDBACK_DISABLED_KEY],
      (result) => {
        const bookmarks = result.bookmarks || [];
        if (!bookmarks.some((b) => b.url === url)) {
          bookmarks.push({ url, title: customTitle, incognito });
          const bookmarkCount = (result[BOOKMARK_COUNT_KEY] || 0) + 1;

          chrome.storage.local.set(
            {
              bookmarks,
              [BOOKMARK_COUNT_KEY]: bookmarkCount,
            },
            () => {
              displayBookmarks();
              chrome.storage.local.getBytesInUse(null, (bytes) => {
                console.log(`Used: ${bytes} bytes`);
              });

              // Show feedback dialog every 5 bookmarks if not disabled
              if (!result[FEEDBACK_DISABLED_KEY] && bookmarkCount % 5 === 0) {
                showFeedbackDialog();
              }
            }
          );
        }
      }
    );
  });
}

window.latencyResults = window.latencyResults || {};

function displayBookmarks() {
  trunOffInstructions();
  chrome.storage.local.get(["bookmarks"], (result) => {
    const bookmarks = result.bookmarks || [];
    const list = document.getElementById("bookmarkList");
    list.innerHTML = "";
    list.style.width = "100%";
    list.style.maxWidth = "420px";
    list.style.margin = "0 auto";

    bookmarks.forEach((bookmark, index) => {
      if (bookmark.type === 'divider') {
        // 渲染分割线（左对齐）
        const li = document.createElement('li');
        li.className = 'flex flex-row items-center w-full my-2';
        li.style.pointerEvents = 'auto';
        li.style.userSelect = 'none';
        li.style.position = 'relative';
        // 拖动排序相关
        li.setAttribute('draggable', 'true');
        li.dataset.divider = 'true';
        li.addEventListener('dragstart', (e) => {
          li.classList.add('opacity-50');
          e.dataTransfer.effectAllowed = 'move';
          e.dataTransfer.setData('application/x-bookmark-index', String(index));
        });
        li.addEventListener('dragend', () => {
          li.classList.remove('opacity-50');
        });
        li.addEventListener('dragover', (e) => {
          e.preventDefault();
          li.classList.add('ring', 'ring-[#45E3B8]', 'ring-2');
        });
        li.addEventListener('dragleave', () => {
          li.classList.remove('ring', 'ring-[#45E3B8]', 'ring-2');
        });
        li.addEventListener('drop', (e) => {
          e.preventDefault();
          li.classList.remove('ring', 'ring-[#45E3B8]', 'ring-2');
          const fromIndex = parseInt(e.dataTransfer.getData('application/x-bookmark-index'), 10);
          const toIndex = index;
          if (!isNaN(fromIndex) && fromIndex !== toIndex && fromIndex >= 0 && toIndex >= 0) {
            const moved = bookmarks.splice(fromIndex, 1)[0];
            bookmarks.splice(toIndex, 0, moved);
            chrome.storage.local.set({ bookmarks }, displayBookmarks);
          }
        });
        // 左侧文本，右侧横线
        li.innerHTML = `${bookmark.text ? `<span class='px-2 text-[#45E3B8] text-xs whitespace-nowrap'>${bookmark.text}</span>` : ''}<div class='flex-1 border-t border-[#45E3B8] opacity-60 mx-2'></div><button class='ml-2 text-yellow-400/80 hover:text-yellow-500 text-base transition-all duration-300 opacity-80 hover:opacity-100 hover:scale-110 active:scale-90 divider-edit-btn' title='编辑分割线'>✏️</button><button class='ml-2 text-red-400/70 hover:text-red-500 text-xl transition-all duration-300 opacity-80 hover:opacity-100 hover:scale-110 active:scale-90 divider-del-btn' title='删除分割线' aria-label='Delete bookmark'><svg width='14' height='14' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'><line x1='4.5' y1='4.5' x2='13.5' y2='13.5' stroke='#ff2e4c' stroke-width='2' stroke-linecap='round'/><line x1='13.5' y1='4.5' x2='4.5' y2='13.5' stroke='#ff2e4c' stroke-width='2' stroke-linecap='round'/></svg></button>`;
        // 删除分割线
        li.querySelector('.divider-del-btn').onclick = (e) => {
          e.stopPropagation();
          bookmarks.splice(index, 1);
          chrome.storage.local.set({ bookmarks }, displayBookmarks);
        };
        // 编辑分割线
        li.querySelector('.divider-edit-btn').onclick = (e) => {
          e.stopPropagation();
          const newText = prompt('请输入新的分割线文本：', bookmark.text || '');
          if (newText !== null) {
            bookmarks[index].text = newText.trim();
            chrome.storage.local.set({ bookmarks }, displayBookmarks);
          }
        };
        list.appendChild(li);
        return;
      }
      const li = document.createElement("li");
      li.className =
        "flex flex-row items-center bg-[#25262b] w-full h-10 p-2 overflow-hidden rounded-xl hover:bg-[#2c2d33] text-gray-300 hover:text-[#45E3B8] transition-all duration-300 shadow-md shadow-black/10 hover:shadow-lg hover:shadow-black/20 border border-gray-700/20 hover:border-gray-700/30 group cursor-pointer mb-2";

      // 拖动排序相关
      li.setAttribute("draggable", "true");
      li.dataset.url = bookmark.url;
      li.addEventListener("dragstart", (e) => {
        li.classList.add("opacity-50");
        e.dataTransfer.effectAllowed = "move";
        e.dataTransfer.setData('application/x-bookmark-index', String(index));
      });
      li.addEventListener("dragend", () => {
        li.classList.remove("opacity-50");
      });
      li.addEventListener("dragover", (e) => {
        e.preventDefault();
        li.classList.add("ring", "ring-[#45E3B8]", "ring-2");
      });
      li.addEventListener("dragleave", () => {
        li.classList.remove("ring", "ring-[#45E3B8]", "ring-2");
      });
      li.addEventListener("drop", (e) => {
        e.preventDefault();
        li.classList.remove("ring", "ring-[#45E3B8]", "ring-2");
        const fromIndex = parseInt(e.dataTransfer.getData('application/x-bookmark-index'), 10);
        const toIndex = index;
        if (!isNaN(fromIndex) && fromIndex !== toIndex && fromIndex >= 0 && toIndex >= 0) {
          const moved = bookmarks.splice(fromIndex, 1)[0];
          bookmarks.splice(toIndex, 0, moved);
          chrome.storage.local.set({ bookmarks }, displayBookmarks);
        }
      });

      const container = document.createElement("div");
      container.className = "flex flex-row items-center min-w-0 p-0 gap-2 flex-1 overflow-hidden";

      const text = document.createElement("div");
      text.textContent = bookmark.title || bookmark.url;
      text.title = bookmark.url;
      text.className =
        "truncate whitespace-nowrap text-sm transition-all duration-300 font-medium leading-none flex-1";

      // 检测延迟结果
      let latencySpan = null;
      if (window.latencyResults[bookmark.url]) {
        latencySpan = document.createElement('span');
        latencySpan.textContent = window.latencyResults[bookmark.url];
        if (window.latencyResults[bookmark.url] === '超时') {
          latencySpan.className = 'ml-2 text-xs px-2 py-1 rounded bg-[#23272e] text-red-400 font-bold';
        } else {
          latencySpan.className = 'ml-2 text-xs px-2 py-1 rounded bg-[#23272e] text-blue-400 font-bold';
        }
      }

      container.appendChild(text);

      // 新增重命名按钮
      const renameBtn = document.createElement("button");
      renameBtn.innerHTML = `<span style='font-size:14px;line-height:1;'>✏️</span>`;
      renameBtn.className =
        "ml-2 text-yellow-400/80 hover:text-yellow-500 text-xl transition-all duration-300 opacity-80 hover:opacity-100 hover:scale-110 active:scale-90";
      renameBtn.setAttribute("aria-label", "Rename bookmark");
      renameBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        const newTitle = prompt("请输入新的书签名称：", bookmark.title || bookmark.url);
        if (newTitle !== null) {
          const trimmed = newTitle.trim();
          if (trimmed) {
            bookmarks[index].title = trimmed;
            chrome.storage.local.set({ bookmarks }, displayBookmarks);
          }
        }
      });
      if (latencySpan) container.appendChild(latencySpan);
      container.appendChild(renameBtn);
      // 增加重命名和删除按钮间距
      const gapSpan = document.createElement('span');
      gapSpan.style.display = 'inline-block';
      gapSpan.style.width = '8px';
      container.appendChild(gapSpan);

      const delBtn = document.createElement("button");
      delBtn.innerHTML = `<svg width='14' height='14' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'><line x1='4.5' y1='4.5' x2='13.5' y2='13.5' stroke='#ff2e4c' stroke-width='2' stroke-linecap='round'/><line x1='13.5' y1='4.5' x2='4.5' y2='13.5' stroke='#ff2e4c' stroke-width='2' stroke-linecap='round'/></svg>`;
      delBtn.className =
        "ml-2 text-red-400/70 hover:text-red-500 text-xl transition-all duration-300 opacity-80 hover:opacity-100 hover:scale-110 active:scale-90";
      delBtn.setAttribute("aria-label", "Delete bookmark");

      delBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        bookmarks.splice(index, 1);
        chrome.storage.local.set({ bookmarks }, displayBookmarks);
      });

      li.addEventListener("click", () => {
        chrome.windows.getCurrent((window) => {
          if (window.incognito === bookmark.incognito) {
            chrome.tabs.create({ url: bookmark.url, windowId: window.id });
          } else {
            chrome.windows.create({
              url: bookmark.url,
              incognito: bookmark.incognito,
            });
          }
        });
      });

      li.appendChild(container);
      li.appendChild(delBtn);
      list.appendChild(li);
    });
  });
}

// Feedback dialog functions
function initializeFeedback() {
  const dialog = document.getElementById("feedbackDialog");
  const dialogContent = dialog.querySelector("div");

  // Review button
  document.getElementById("feedbackReview").addEventListener("click", () => {
    chrome.storage.local.set({ [FEEDBACK_DISABLED_KEY]: true }, () => {
      window.open(CHROME_STORE_URL, "_blank");
      hideFeedbackDialog();
    });
  });

  // Later button
  document
    .getElementById("feedbackLater")
    .addEventListener("click", hideFeedbackDialog);

  // Never button
  document.getElementById("feedbackNever").addEventListener("click", () => {
    chrome.storage.local.set(
      { [FEEDBACK_DISABLED_KEY]: true },
      hideFeedbackDialog
    );
  });

  // Handle click outside the dialog
  dialog.addEventListener("click", (e) => {
    if (e.target === dialog) {
      hideFeedbackDialog();
    }
  });
}

function showFeedbackDialog() {
  const dialog = document.getElementById("feedbackDialog");
  const dialogContent = dialog.querySelector("div");

  dialog.classList.remove("hidden");
  dialog.classList.add("flex");

  // Trigger animation
  requestAnimationFrame(() => {
    dialogContent.classList.remove("scale-95", "opacity-0");
    dialogContent.classList.add("scale-100", "opacity-100");
  });
}

function hideFeedbackDialog() {
  const dialog = document.getElementById("feedbackDialog");
  const dialogContent = dialog.querySelector("div");

  dialogContent.classList.remove("scale-100", "opacity-100");
  dialogContent.classList.add("scale-95", "opacity-0");

  setTimeout(() => {
    dialog.classList.remove("flex");
    dialog.classList.add("hidden");
  }, 300); // Match the duration in the CSS transition
}

// Backup functions
// 修改showBackupDialog函数，自动填充密码和勾选状态
function showBackupDialog() {
  const dialog = document.getElementById("backupDialog");
  const dialogContent = dialog.querySelector("div");

  // Load saved WebDAV settings
  chrome.storage.local.get(["webdavUrl", "webdavUsername", "webdavPassword"], (result) => {
    if (result.webdavUrl) {
      document.getElementById("webdavUrl").value = result.webdavUrl;
    }
    if (result.webdavUsername) {
      document.getElementById("webdavUsername").value = result.webdavUsername;
    }
    if (result.webdavPassword) {
      document.getElementById("webdavPassword").value = result.webdavPassword;
      document.getElementById("rememberWebdavPassword").checked = true;
    } else {
      document.getElementById("webdavPassword").value = '';
      document.getElementById("rememberWebdavPassword").checked = false;
    }
  });

  dialog.classList.remove("hidden");
  dialog.classList.add("flex");

  // Trigger animation
  requestAnimationFrame(() => {
    dialogContent.classList.remove("scale-95", "opacity-0");
    dialogContent.classList.add("scale-100", "opacity-100");
  });

  // Add event listeners
  document.getElementById("backupNow").addEventListener("click", performBackup);
  document.getElementById("restoreFromBackup").addEventListener("click", showRestoreList);

  // Handle click outside the dialog
  dialog.addEventListener("click", (e) => {
    if (e.target === dialog) {
      hideBackupDialog();
    }
  });
}

function hideBackupDialog() {
  const dialog = document.getElementById("backupDialog");
  const dialogContent = dialog.querySelector("div");

  dialogContent.classList.remove("scale-100", "opacity-100");
  dialogContent.classList.add("scale-95", "opacity-0");

  setTimeout(() => {
    dialog.classList.remove("flex");
    dialog.classList.add("hidden");
  }, 300);
}

function showBackupStatus(message, isError = false) {
  const statusDiv = document.getElementById("backupStatus");
  const statusText = document.getElementById("backupStatusText");
  
  statusText.textContent = message;
  statusText.className = `text-sm ${isError ? 'text-red-400' : 'text-green-400'}`;
  statusDiv.classList.remove("hidden");
  
  setTimeout(() => {
    statusDiv.classList.add("hidden");
  }, 3000);
}

// 修改performBackup和performRestore，处理记住密码逻辑
async function performBackup() {
  const url = document.getElementById("webdavUrl").value.trim();
  const username = document.getElementById("webdavUsername").value.trim();
  const password = document.getElementById("webdavPassword").value;
  const remember = document.getElementById("rememberWebdavPassword").checked;

  if (!url || !username || !password) {
    showBackupStatus("请填写完整的WebDAV信息", true);
    return;
  }

  try {
    // Save WebDAV settings
    chrome.storage.local.set({ webdavUrl: url, webdavUsername: username });
    if (remember) {
      chrome.storage.local.set({ webdavPassword: password });
    } else {
      chrome.storage.local.remove("webdavPassword");
    }

    // Get all extension data
    const data = await new Promise((resolve) => {
      chrome.storage.local.get(null, resolve);
    });

    // Create backup data
    const backupData = {
      version: "1.0",
      timestamp: new Date().toISOString(),
      data: data
    };

    const backupJson = JSON.stringify(backupData, null, 2);
    const backupBlob = new Blob([backupJson], { type: 'application/json' });

    // Upload to WebDAV
    const response = await uploadToWebDAV(url, username, password, backupBlob);
    
    if (response.ok) {
      // 新增弹窗提示
      alert("备份成功！");
      showBackupStatus("备份成功！");
      hideBackupDialog();
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error) {
    console.error("Backup failed:", error);
    showBackupStatus(`备份失败: ${error.message}`, true);
  }
}

// 1. 新增：显示备份文件列表并选择恢复
async function showRestoreList() {
  const url = document.getElementById("webdavUrl").value.trim();
  const username = document.getElementById("webdavUsername").value.trim();
  const password = document.getElementById("webdavPassword").value;
  if (!url || !username || !password) {
    showBackupStatus("请填写完整的WebDAV信息", true);
    return;
  }
  const auth = btoa(`${username}:${password}`);
  try {
    const listResponse = await fetch(url, {
      method: 'PROPFIND',
      headers: {
        'Authorization': `Basic ${auth}`,
        'Depth': '1'
      }
    });
    if (!listResponse.ok) throw new Error('无法获取备份列表');
    const xmlText = await listResponse.text();
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
    const hrefs = xmlDoc.querySelectorAll('href');
    const files = Array.from(hrefs)
      .map(href => href.textContent)
      .filter(href => href.includes('bookmark-backup-') && href.endsWith('.json'))
      .sort()
      .reverse();
    if (files.length === 0) {
      showBackupStatus("没有可用的备份文件", true);
      return;
    }
    // 解析文件名和时间
    const fileList = files.map(f => {
      let name = f.split('/').pop();
      let match = name.match(/bookmark-backup-(\d{8})-(\d{6})\.json/);
      let time = '';
      if (match) {
        const d = match[1], t = match[2];
        time = `${d.slice(0,4)}-${d.slice(4,6)}-${d.slice(6,8)} ${t.slice(0,2)}:${t.slice(2,4)}:${t.slice(4,6)}`;
      }
      return { url: f, name, time };
    });
    // 显示在独立弹窗
    const restoreDialog = document.getElementById('restoreDialog');
    const listDiv = document.getElementById('restoreFileList');
    listDiv.innerHTML = fileList.map(f => `
      <div style="display:flex;align-items:center;width:100%;">
        <button class="restore-file-btn" data-url="${f.url}" title="${f.name}" style="flex:1 1 auto;">
          <span class="restore-file-name">${f.name}</span>
          <span class="restore-file-time">${f.time}</span>
        </button>
        <button class="delete-backup-btn" data-url="${f.url}" title="删除备份" aria-label="删除">
          <svg width="14" height="14" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
            <line x1="4.5" y1="4.5" x2="13.5" y2="13.5" stroke="#ff2e4c" stroke-width="2" stroke-linecap="round"/>
            <line x1="13.5" y1="4.5" x2="4.5" y2="13.5" stroke="#ff2e4c" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
    `).join('');
    restoreDialog.classList.remove('hidden');
    restoreDialog.classList.add('flex');
    // 绑定点击事件
    Array.from(listDiv.querySelectorAll('button.restore-file-btn')).forEach(btn => {
      btn.onclick = async () => {
        if (!confirm('确定要恢复此备份吗？这将覆盖当前的所有数据。')) return;
        const fileUrl = btn.getAttribute('data-url');
        let downloadUrl = fileUrl;
        if (!/^https?:/.test(fileUrl)) {
          if (fileUrl.startsWith('/')) {
            const urlObj = new URL(url);
            downloadUrl = urlObj.origin + fileUrl;
          } else {
            downloadUrl = url + (url.endsWith('/') ? '' : '/') + fileUrl;
          }
        }
        const resp = await fetch(downloadUrl, {
          method: 'GET',
          headers: { 'Authorization': `Basic ${auth}` }
        });
        if (!resp.ok) {
          showBackupStatus('下载失败', true);
          return;
        }
        const backupData = await resp.json();
        if (!backupData.data) {
          showBackupStatus('无效的备份文件格式', true);
          return;
        }
        await new Promise((resolve) => {
          chrome.storage.local.clear(() => {
            chrome.storage.local.set(backupData.data, resolve);
          });
        });
        showBackupStatus('恢复成功！');
        restoreDialog.classList.remove('flex');
        restoreDialog.classList.add('hidden');
        hideBackupDialog();
        displayBookmarks();
      };
    });
    // 删除按钮事件
    Array.from(listDiv.querySelectorAll('button.delete-backup-btn')).forEach(btn => {
      btn.onclick = async (e) => {
        e.stopPropagation();
        if (!confirm('确定要删除此备份文件吗？')) return;
        const fileUrl = btn.getAttribute('data-url');
        let deleteUrl = fileUrl;
        if (!/^https?:/.test(fileUrl)) {
          if (fileUrl.startsWith('/')) {
            const urlObj = new URL(url);
            deleteUrl = urlObj.origin + fileUrl;
          } else {
            deleteUrl = url + (url.endsWith('/') ? '' : '/') + fileUrl;
          }
        }
        const resp = await fetch(deleteUrl, {
          method: 'DELETE',
          headers: { 'Authorization': `Basic ${auth}` }
        });
        if (resp.ok) {
          showBackupStatus('删除成功！');
          btn.parentElement.remove();
        } else {
          showBackupStatus('删除失败', true);
        }
      };
    });
    // 关闭按钮
    document.getElementById('closeRestoreDialog').onclick = () => {
      restoreDialog.classList.remove('flex');
      restoreDialog.classList.add('hidden');
    };
  } catch (e) {
    showBackupStatus('获取备份列表失败', true);
  }
}

async function uploadToWebDAV(url, username, password, blob) {
  const now = new Date();
  const pad = n => n.toString().padStart(2, '0');
  const filename = `bookmark-backup-${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.json`;
  const fullUrl = url.endsWith('/') ? url + filename : url + '/' + filename;
  
  const auth = btoa(`${username}:${password}`);
  
  return fetch(fullUrl, {
    method: 'PUT',
    headers: {
      'Authorization': `Basic ${auth}`,
      'Content-Type': 'application/json',
      'Content-Length': blob.size.toString()
    },
    body: blob
  });
}

async function downloadFromWebDAV(url, username, password) {
  // Try to find the most recent backup file
  const auth = btoa(`${username}:${password}`);
  
  // First, try to list files to find the most recent backup
  try {
    const listResponse = await fetch(url, {
      method: 'PROPFIND',
      headers: {
        'Authorization': `Basic ${auth}`,
        'Depth': '1'
      }
    });
    
    if (listResponse.ok) {
      const xmlText = await listResponse.text();
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
      
      // Find backup files
      const hrefs = xmlDoc.querySelectorAll('href');
      const backupFiles = Array.from(hrefs)
        .map(href => href.textContent)
        .filter(href => href.includes('bookmark-backup-') && href.endsWith('.json'))
        .sort()
        .reverse();
      
      if (backupFiles.length > 0) {
        let latestBackup = backupFiles[0];
        let downloadUrl = latestBackup;

        // 如果是以http/https开头，直接用
        if (latestBackup.startsWith('http')) {
          downloadUrl = latestBackup;
        }
        // 如果是以/开头，拼接主机名
        else if (latestBackup.startsWith('/')) {
          const urlObj = new URL(url);
          downloadUrl = urlObj.origin + latestBackup;
        }
        // 否则认为是相对路径
        else {
          downloadUrl = url + (url.endsWith('/') ? '' : '/') + latestBackup;
        }

        return fetch(downloadUrl, {
          method: 'GET',
          headers: {
            'Authorization': `Basic ${auth}`
          }
        });
      }
    }
  } catch (error) {
    console.warn("Could not list files, trying direct download:", error);
  }
  
  // Fallback: try to download a backup file with today's date
  const filename = `bookmark-backup-${new Date().toISOString().split('T')[0]}.json`;
  const fullUrl = url.endsWith('/') ? url + filename : url + '/' + filename;
  
  return fetch(fullUrl, {
    method: 'GET',
    headers: {
      'Authorization': `Basic ${auth}`
    }
  });
}
